﻿// 文件名：函数和C-风格字符串
// 创建时间：2021/6/21/星期一 15:53:37

#include <iostream>
using namespace std;


//计算特定的字符在字符串中出现的次数
unsigned int c_in_str(const char* str, char ch);
void strgfun()
{
	char mmm[15] = "minimum";
	const char* wail = "ululate";
	unsigned int ms = c_in_str(mmm, 'm');
	unsigned int us = c_in_str(wail, 'u');
	cout << "mmm中出现m的次数为： " << ms << endl;
	cout << "wail中出现u的次数为： " << us << endl;
}

unsigned int c_in_str(const char* str, char ch)
{
	unsigned int count = 0;
	while (*str) //当遇到空字符'\0'时停止
	{
		if (*str == ch)
		{
			count++;
		}
		str++;
	}
	return count;
}

//返回C-风格字符串的函数
char* buildstr(char ch, int time);
void strgback()
{
	int times;
	char ch;
	cout << "Enter a character: ";
	cin >> ch;
	cout << "Enter an integer: ";
	cin >> times;
	char* ps = buildstr(ch, times); //返回的是字符串的地址
	cout << ps << endl;
	delete [] ps;
	ps = buildstr('+', 10);
	cout << ps << endl;
	delete[] ps;

}

char* buildstr(char ch, int n)
{
	char* pstr = new char[n+1];
	pstr[n] = '\0';//设置C-风格字符串最后一位是空字符
	while(n-- > 0)//先判断后减一
	{
		pstr[n] = ch;
		//cout << n << endl;
	}
	return pstr; // 返回指针char*
}



int main()
{
	/*
	用字符串做函数参数的传递方法：
	1、char数组；
	2、用引号括起来的字符串常量（字符串字面值）
	3、被设置为字符串的地址的指针
		————类型都是char*
	*/
	char ghost[15] = "gaadnvdinad";
	const char* str = "gaadgsnvdinad";
	int n1 = strlen(ghost);
	int n2 = strlen(str);
	int n3 = strlen("gaadnvdinad");
	int n4 = strlen("gaadgsnvdinad");
	cout << "strlen(ghost) = " << n1 << endl;
	cout << "strlen(str) = " << n2 << endl;
	cout << "strlen('gaadnvdinad') = " << n3 << endl;
	cout << "strlen('gaadgsnvdinad') = " << n4 << endl;

	//调用函数统计特定字符出现的次数
	//strgfun();

	//返回C-风格字符串
	strgback();

	system("pause");
	return 0;
}